<?php
namespace app\serveruser\logic;

use \app\manage\logic\BaseLogic;
use \app\manage\service\ApiBase;

// 用户微应用下的逻辑层
class User extends BaseLogic
{

	protected $userValidate = '\app\serveruser\validate\User';
    protected $userLogic = '\app\serveruser\logic\User';

	/*用户登录*/
    public function login($data): array 
    {
        $service = new ApiBase($data['token']);
        //获取token内容
        $getToken['query'] = json_encode([
            ['path'=>'serveruser/auth/Token/hGetAll', 'param'=>['token'=>$data['token']]]
        ]);
        $tokenContent = ApiBase::sendDataOne(config('proxy_queue_url'), $getToken);
        if($tokenContent['status'] != SUCCESS_STATUS){
            return $tokenContent;
        }
        if($tokenContent['res']['no_user_err_counts'] >= MAX_LOGIN_ERR_TIMES){
            $checkAuthCode = $this->_checkAuthCode($data);
            if($checkAuthCode['status'] != SUCCESS_STATUS){
                return verify_err($tokenContent['res'], '验证图形验证码失败');
            }
        }
        //根据name获取用户信息中的login_err_times,用于判断是否检验图形验证码
        $getBase['query'] = json_encode([
            ['path'=>'serveruser/user/User/info', 'param'=>['name'=>$data['name'],'is_add_no_user_counts'=>1,'token'=>$data['token']]]
        ]);
        $baseInfo = ApiBase::sendDataOne(config('proxy_queue_url'), $getBase);
        if($baseInfo['status'] != SUCCESS_STATUS){
            $tokenContent['res']['no_user_err_counts'] = $tokenContent['res']['no_user_err_counts'] + 1;
            return verify_err($tokenContent['res'], '没有相关用户信息');
        }
        //判断是否为管理员登录
        if($baseInfo['res']['id'] > MAX_SYSTEM_ID){
        	return verify_err(null, '非管理员不能进行登录后台');
        }
        //判断：若次数大于所允许的错误登录次数：验证图形验证码
        if($baseInfo['res']['login_err_times'] >= MAX_LOGIN_ERR_TIMES && !isset($checkAuthCode)){
            $checkAuthCode = $this->_checkAuthCode($data);
            if($checkAuthCode['status'] != SUCCESS_STATUS){
                $checkAuthCode['res']['last_err_login_time'] = $baseInfo['res']['last_err_login_time'];
                $checkAuthCode['res']['login_err_times'] = $baseInfo['res']['login_err_times'];
                $checkAuthCode['res']['max_login_err_times'] = MAX_LOGIN_ERR_TIMES;
                $checkAuthCode['res']['no_user_err_counts'] = $tokenContent['res']['no_user_err_counts'];
                return $checkAuthCode;
            }
        }
        //登录并获取用户信息 若第一次打勾自动登录 返回auto_login_token信息
        $sendData['query'] = json_encode([
            ['path'=>'serveruser/user/User/login', 'param'=>$data]
        ]);
        $loginInfoRes = ApiBase::sendDataOne(config('proxy_all_url'), $sendData);
        if($loginInfoRes['status'] != SUCCESS_STATUS){
            return verify_err($loginInfoRes['res'], $loginInfoRes['msg']);
        }
        //获取用户的资金信息  不可在service里的登录方法中验证
        $fundInfo = $service->oneStepRun(['user_id'=>$baseInfo['res']['id']], 'serverfund/fund/FundAccount/userFund', '', 1, $this->userValidate, $this->userLogic);
        if($fundInfo['status'] != SUCCESS_STATUS){
            return $fundInfo;
        }
        //组装用户信息
        $allInfo = array_merge($loginInfoRes['res'], $fundInfo['res']);
        $allInfo && $allInfo['earnings'] = 0;
        return auto_return($allInfo, '成功获取用户信息', '获取用户信息失败');
    }

    /*验证图形验证码*/
    public function _checkAuthCode($data): array 
    {
        $checkImg['type'] = $data['img_type'];
        $checkImg['code_id'] = $data['img_code_id'];
        $checkImg['auth_code'] = $data['auth_code'];
        $checkImg['token'] = $data['token'];
        $checkImg['appkey'] = \app\manage\service\ApiBase::getAppKey();
        $sendData['query'] = json_encode([
            ['path'=>'serverauthcode/authcode/ApiAuthCode/verifyAuthCode', 'param'=>$checkImg]
        ]);
        return ApiBase::sendDataOne(config('proxy_all_url'), $sendData);
    }

    public function addManager($data): array 
    {
        //添加管理员
        $service = new ApiBase($data['token']);
        $addManagerData['name'] = $data['name'];
        $addManagerData['nickname'] = $data['name'];
        $addManagerData['phone'] = $data['phone'];
        $addManagerData['login_password'] = $data['login_password'];
        $addManagerData['token'] = $data['token'];
        $addManagerRes = $service->oneStepRun($addManagerData, 'serveruser/user/User/addManager', '', 1, $this->userValidate, $this->userLogic);
        if($addManagerRes['status'] != SUCCESS_STATUS){
            return $addManagerRes;
        }
        //获取app_id
        $app_key = ApiBase::getAppKey();
        $getAppRes = $service->oneStepRun(['app_key'=>$app_key], 'serveruser/auth/App/find', '', 1, $this->userValidate, $this->userLogic);
        if($getAppRes['status'] != SUCCESS_STATUS){
            return $getAppRes;
        }
        //获取发送支付密码的云片短信配置
        $getSmsRes = $service->oneStepRun(['action'=>'yayiSendPayPwd','app_id'=>$getAppRes['res']['id']], 'serversms/sms/Sms/smsInfo', '', 1, $this->userValidate, $this->userLogic);
        if($getSmsRes['status'] != SUCCESS_STATUS){
            return $getSmsRes;
        }
        //发送请求
        $init['app_id'] = $getAppRes['res']['id'];
        $init['user_id'] = $addManagerRes['res']['autoRes'];
        $init['create_ip'] = request()->ip();
        $initPayPwd['id'] = $addManagerRes['res']['autoRes'];
        $initPayPwd['login_password'] = $data['login_password'];
        $initPayPwd['pay_password'] = mt_rand(100000,999999);
        $sendPayPwdSms['send_info'] = $getSmsRes['res']['sms_info'];  //当前域名 $request->domain(); 
        $sendPayPwdSms['send_info']['text'] = str_replace("#code#",$initPayPwd['pay_password'],$sendPayPwdSms['send_info']['text']); 
        $sendPayPwdSms['send_info']['text'] = str_replace("#website#",request()->domain(),$sendPayPwdSms['send_info']['text']); 
        $sendPayPwdSms['send_info']['mobile'] = $data['phone'];
        $checkAuth = 'serverfund/fund/FundAccount/init,serverfund/integral/IntegralAccount/init,serverfund/currency/CurrencyAccount/init,serveruser/user/User/initPayPassword';
        $queryData = [
            ['path'=>'serverfund/fund/FundAccount/init', 'param'=>$init],
            ['path'=>'serverfund/integral/IntegralAccount/init', 'param'=>$init],
            ['path'=>'serverfund/currency/CurrencyAccount/init', 'param'=>$init],
            ['path'=>'serveruser/user/User/initPayPassword', 'param'=>$initPayPwd]
        ];
        $res = $service->lotsStepRun($data, $queryData, $checkAuth, '', 1, $this->userValidate, $this->userLogic);
        if($res['status'] != SUCCESS_STATUS){
            return $res;
        }

        //发送初始化支付密码通知短信
        $sendSmsRes = $service->oneStepRun($sendPayPwdSms, 'serversms/sms/Sms/sendOne', '', 1, $this->userValidate, $this->userLogic);
        if($sendSmsRes['status'] != SUCCESS_STATUS){
            return $sendSmsRes;
        }

        return auto_success($res, '添加成功');
    }


}
